package com.lzw.breezeNovel.webApp.service.impl.comic;

import com.lzw.breezeNovel.common.exception.BaseException;
import com.lzw.breezeNovel.common.login.LoginUser;
import com.lzw.breezeNovel.common.login.LoginUserHolder;
import com.lzw.breezeNovel.common.result.ResultCodeEnum;
import com.lzw.breezeNovel.model.entity.pojo.comic.ComicComment;
import com.lzw.breezeNovel.model.entity.pojo.user.UserInfo;
import com.lzw.breezeNovel.model.entity.query.PaginationResultQuery;
import com.lzw.breezeNovel.webApp.mapper.comic.ComicCommentMapper;
import com.lzw.breezeNovel.webApp.mapper.user.UserInfoMapper;
import com.lzw.breezeNovel.webApp.service.comic.ComicCommentService;
import com.lzw.breezeNovel.webApp.vo.comic.ComicCommentVo;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.service.impl.comic
 * @date 2025/3/16
 * @description 用户评论表
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class ComicCommentServiceImpl implements ComicCommentService {

    /**
     * 注入评论mapper
     */
    @Autowired
    private ComicCommentMapper comicCommentMapper;
    /**
     * 注入用户信息
     */
    @Autowired
    private UserInfoMapper userInfoMapper;


    /**
     * 获取评论
      * @param comicId
     * @param pageNo
     * @param size
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public PaginationResultQuery<ComicCommentVo> selectByComicId(Long comicId, Integer pageNo, Integer size) {
        //计算分页
        Integer start = getStart(pageNo, size);
        //根据书籍id查询评论
        Long count = comicCommentMapper.selectByComicId(comicId);
        //判断是否有评论
        if (count == 0) {
            return new PaginationResultQuery<>(Math.toIntExact(count), size, pageNo, null);
        }
        //获取评论
        List<ComicComment> comicCommentVos = comicCommentMapper.selectComicCommentByComicId(comicId, start, size);
        //对评论进行拷贝
        List<ComicCommentVo> comicCommentVoList = Copy(comicCommentVos);
        //封装对象
        return new PaginationResultQuery<>(Math.toIntExact(count), size, pageNo, comicCommentVoList);
    }

    /**
     * 发布评论
     * @param comicId
     * @param content
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publishComment(Long comicId, String content) {
        //获取用户id
        Long userId = getUserId();
        //创建评论对象
        ComicComment comicComment = new ComicComment();
        //设置漫画id
        comicComment.setComicId(Math.toIntExact(comicId));
        //设置用户id
        comicComment.setUserId(Math.toIntExact(userId));
        //设置评论内容
        comicComment.setContent(content);
        //设置评论时间
        comicComment.setCreateTime(new Date());
        //设置获赞人数
        comicComment.setLikes(0);
        //设置更新时间
        comicComment.setUpdateTime(new Date());
        //保存评论
        comicCommentMapper.insert(comicComment);
    }

    /**
     * 计算分页数据
     */
    @NotNull
    private Integer getStart(Integer pageNo, Integer size) {
        // 对分页参数进行校验，使用Optional简化代码
        pageNo = Optional.ofNullable(pageNo).orElse(1);
        size = Optional.ofNullable(size).orElse(10);
        pageNo = Math.max(pageNo, 1);
        size = Math.max(size, 1);
        return (pageNo - 1) * size;
    }

    /**
     * 拷贝评论
     */
    @Nullable
    @Contract(pure = true)
    private List<ComicCommentVo> Copy(List<ComicComment> comicCommentVos) {
        //判断是否有数据
        if (comicCommentVos == null || comicCommentVos.size() == 0) {
            return null;
        }
       return comicCommentVos.stream().map(comicComment -> {
            //创建评论对象
            ComicCommentVo comicCommentVo = new ComicCommentVo();
            //拷贝评论
            BeanUtils.copyProperties(comicComment, comicCommentVo);
            //获取用户信息
            UserInfo userInfo = comicComment.getUserInfo();
            //设置用户名称
            comicCommentVo.setUsername(userInfo.getUsername());
            //设置用户头像
            comicCommentVo.setAvatar(userInfo.getAvatar());
           // 获取时间
           Date createTime = comicComment.getCreateTime();
           // 将 Date 转换为 LocalDateTime
           LocalDateTime localDateTime = createTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
           // 定义日期格式
           DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
           // 格式化 LocalDateTime
           comicCommentVo.setData(formatter.format(localDateTime));
           return comicCommentVo;
        }).collect(Collectors.toList());
    }

    /**
     * 获取用户id
     */
    @Transactional(readOnly = true)
    private Long getUserId() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //判断用户是否登录
        if (loginUser == null) {
            throw new BaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }
        String phone = loginUser.getPhone();
        //根据手机号查询用户id
        UserInfo userInfo = userInfoMapper.selectByPhone(phone);
        return userInfo.getUserId();
    }

}
